/**
Sayfa yüklenir yüklenmez bir periyodik-ajax ayarlanacak ve o anki oturuma ait veritabanında 
herhangi bir kayıt varsa onu ekrana getirecek. Ve bu işlem periyodik olarak yapılacak.
*/

YAHOO.namespace("YuiChat");

var $Tool		= YAHOO.tool,
	$Util 		= YAHOO.util,
	$Dom		= YAHOO.util.Dom,
	$Event 		= YAHOO.util.Event,
	$UserAction = YAHOO.util.UserAction,	
	$Assert		= YAHOO.util.Assert,
	$Lang		= YAHOO.lang,
	$Json		= YAHOO.lang.JSON,
	YCH 		= YAHOO.YuiChat;


YCH.ChatClass = {
		
	connected : false,
	channelId : null,	
	me : null,	
	stranger : null,
	lastReadTime : null,
	
	
	read : function(){	
		if(YCH.ChatClass.connected == false) return false;
		var sUrl = 'handleRequests.php?action=read&channelId='+YCH.ChatClass.channelId+'&timestamp='+YCH.ChatClass.lastReadTime;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);
	},
	
	write : function(message){		
		var sUrl = 'handleRequests.php?action=write&channelId=' + YCH.ChatClass.channelId + '&message=' + message +
						'&me='+YCH.ChatClass.me + '&stranger=' + YCH.ChatClass.stranger;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);	
	},
	
	checkChannel : function(){
		if(YCH.ChatClass.connected == true) return false;
		var sUrl = 'handleRequests.php?action=checkChannel&channelId=' + YCH.ChatClass.channelId + "&me=" + YCH.ChatClass.me;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);		
	},
	
	heartBeat : function(){	
		if(YCH.ChatClass.connected == false) return false;
		var sUrl = 'handleRequests.php?action=heartBeat&channelId=' + YCH.ChatClass.channelId + "&me=" + YCH.ChatClass.me;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);
	},
	
	disconnect : function(){
		var sUrl = 'handleRequests.php?action=disconnect&channelId=' + YCH.ChatClass.channelId;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);
	},
	
	online : function(){
		var sUrl = 'handleRequests.php?action=online';
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);
	},
	
	connect : function(){
	
		$Dom.get("sbSex").disabled = "disabled";
		$Dom.get("btnConnect").disabled = "disabled";
		
		YCH.ConnectionXHR.startRequest();	
	},

	sendMessage : function(){
		
		//TODO Zararlı karakterlerden temizle
		 	
		if($Lang.trim($Dom.get("txtMessage").value).length > 0){
					
			YCH.ChatClass.write($Dom.get("txtMessage").value);
			$Dom.get("txtMessage").value = "";
			
		}	
	}
	
	
};

YCH.ConnectionXHR = {

	handleSuccess:function(responseObj){
	
		$answerJson = $Json.parse(responseObj.responseText);
	
		var returnMsg 	= $answerJson.msg;
		 
		if(returnMsg === "connected" ){	
			
			if(YCH.ChatClass.connected == true) return false;
			
			YCH.ChatClass.connected = true;
			
			var me 			= $answerJson.me;
			var stranger 	= $answerJson.stranger;			
			var channelId	= $answerJson.channelId;
			var timestamp 	= $answerJson.timestamp; 
			
			YCH.ChatClass.channelId = channelId;
			YCH.ChatClass.me = me;
			YCH.ChatClass.stranger = stranger;
			YCH.ChatClass.lastReadTime = timestamp;			
			
			$Dom.get("messageBoard").innerHTML += "<br/>connected! <br />";			
			$Dom.get("btnSend").disabled = null;	
			$Dom.get("txtMessage").disabled = null;
			$Dom.get("btnDisconnect").disabled = null;
			
			YCH.ChatClass.read();	
			YCH.ChatClass.heartBeat();
			
		}else if(returnMsg === "connectionWAITING"){
			
			var me 			= $answerJson.me;						
			var channelId	= $answerJson.channelId;
			var timestamp 	= $answerJson.timestamp;
			
			YCH.ChatClass.channelId = channelId;
			YCH.ChatClass.me = me;
			
			$Dom.get("messageBoard").innerHTML = "trying connection!  --  ";
			
			var cancelLink = $Dom.get("messageBoard").appendChild(document.createElement("a"));
			cancelLink.id = "cancelLink";
			cancelLink.appendChild(document.createTextNode("Cancel!"));
			$Event.addListener($Dom.get(cancelLink), "click", YCH.ChatClass.disconnect);
			
			setTimeout(YCH.ChatClass.checkChannel, 3000);
			YCH.ChatClass.heartBeat();
			
			
		}else if(returnMsg === "read"){	
			
			YCH.ChatClass.lastReadTime = $answerJson.timestamp;		
			
			for(var i=0; i < $answerJson.messages.length; i++){
			
				var currentMessage = $answerJson.messages[i];
				
				if(currentMessage.messageFrom === YCH.ChatClass.me){
				
					$Dom.get("messageBoard").innerHTML += "me : " + currentMessage.message + " ( " + currentMessage.createdTime + " ) " + "<br />";
				
				}else{
					$Dom.get("messageBoard").innerHTML += "stranger : " + currentMessage.message + " ( " + currentMessage.createdTime + " ) " + "<br />";
				}			
			}
			
			setTimeout(YCH.ChatClass.read, 2000);
		
		}else if(returnMsg === "noMessage"){			
			setTimeout(YCH.ChatClass.read, 2000);
			
		}else if(returnMsg === "heartBeat"){
						
			setTimeout(YCH.ChatClass.heartBeat, 3000);
		}else if(returnMsg === "strangerIsDisconnected"){
			
			YCH.ChatClass.connected = false;			
	
			$Dom.get("messageBoard").innerHTML += "<br/> Stranger is disconnected!<br />";
			
			$Dom.get("btnConnect").disabled = null;	
			$Dom.get("sbSex").disabled = null;
			
			$Dom.get("btnSend").disabled = "disabled";	
			$Dom.get("txtMessage").disabled = "disabled";
			$Dom.get("btnDisconnect").disabled = "disabled";
			
				
		}else if(returnMsg === "online"){	
			
			$Dom.get("online").innerHTML = $answerJson.counter;
			
		}else if(returnMsg === "writeFAILED"){			
			/*10 kere dön ve yollamaya çalış.Hala yollanmazsa iptal et.*/			
		}else if(returnMsg === "writeOK"){				
			/*yazım işlemi başarılıysa hiçbir şey yapma*/			
		}else if(returnMsg === "disconnected"){
			
			var me 			= $answerJson.me;						
			var channelId	= $answerJson.channelId;
			var timestamp 	= $answerJson.timestamp;
			
			YCH.ChatClass.connected = false;
			
			$Dom.get("messageBoard").innerHTML += "<br/> connection has just cancelled!";
			
			$Dom.get("btnConnect").disabled = null;	
			$Dom.get("sbSex").disabled = null;
			
			$Dom.get("btnSend").disabled = "disabled";	
			$Dom.get("txtMessage").disabled = "disabled";
			$Dom.get("btnDisconnect").disabled = "disabled";
			
		}
				
	},

	handleFailure:function(responseObject){
		
	},
	
	startRequest:function() {
		
		var sUrl = 'handleRequests.php?action=connect&sexPrefer='+$Dom.get("sbSex").value;
		$Util.Connect.asyncRequest('GET', sUrl, YCH.ConnectionCallback);
				
	}

};

YCH.ConnectionCallback = {
		
	success:YCH.ConnectionXHR.handleSuccess,
	failure:YCH.ConnectionXHR.handleFailure,
	scope:YCH.ConnectionXHR
};

$Event.onDOMReady(function (){

	$Dom.get("btnSend").disabled = "disabled";	
	$Dom.get("txtMessage").disabled = "disabled";
	$Dom.get("btnDisconnect").disabled = "disabled";
	
	$Dom.get("btnConnect").disabled = null;	
	$Dom.get("sbSex").disabled = null;
	
	$Event.addListener("btnSend", "click",YCH.ChatClass.sendMessage);	
	//$Event.addListener("txtMessage", "keydown", function(){YCH.sendMessage(false);});	
	var myListener = new $Util.KeyListener("txtMessage", {keys:13}, YCH.ChatClass.sendMessage);
	myListener.enable();
	
	$Event.addListener("btnDisconnect", "click", YCH.ChatClass.disconnect);	
	$Event.addListener("btnConnect", "click", YCH.ChatClass.connect);
	
	YCH.ChatClass.online();
	YCH.onlineIntervalId = setInterval(YCH.ChatClass.online, 20000);
	
});